package com.xii.controller;

import com.xii.constant.MessageConstant;
import com.xii.entity.Result;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 得到用户名
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @GetMapping("/getUsername")
    @ResponseBody
    public Result getUsername(){
        try {
            //从安全框架中中拿出user这个对象 返回用户名
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if(user == null){
                return new Result(false,MessageConstant.GET_USERNAME_FAIL);
            }
            String username = user.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_USERNAME_FAIL);
        }
    }



}
